<template>
	<view class="login-container">
		<!-- Logo和标题 -->
		<view class="logo-section">
			<view class="logo"></view>
			<text class="app-title">六堡商城</text>
		</view>

		<!-- 登录模式切换 -->
		<view class="login-mode-tabs">
			<view class="tab-item" :class="{ active: loginMode === 'wechat' }" @click="switchLoginMode('wechat')">
				<text class="tab-text">微信登录</text>
			</view>
			<view class="tab-item" :class="{ active: loginMode === 'phone' }" @click="switchLoginMode('phone')">
				<text class="tab-text">手机登录</text>
			</view>
		</view>

		<!-- 微信登录：getUserInfo、getPhoneNumber -->
		<view v-if="loginMode === 'wechat'" class="wechat-login-section">
			<!-- <button class="auth-btn wechat-btn" open-type="getUserInfo" @getuserinfo="onGetUserInfo"
				:disabled="authLoading">
				<text class="btn-icon">📱</text>
				<text class="btn-text">{{ authLoading ? '授权中...' : '微信快捷登录' }}</text>
			</button> -->
			<button class="auth-btn wechat-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
				:disabled="authLoading">
				<text class="btn-icon">📱</text>
				<text class="btn-text">{{ authLoading ? '授权中...' : '微信快捷登录' }}</text>
			</button>
		</view>

		<!-- 手机登录 -->
		<view v-if="loginMode === 'phone'" class="phone-login-section">
			<!-- 手机号输入 -->
			<view class="form-item">
				<view class="input-wrapper">
					<text class="input-icon">📱</text>
					<input class="form-input" v-model="phoneForm.mobile" placeholder="请输入手机号" type="number"
						maxlength="11" />
				</view>
			</view>

			<!-- 登录方式切换 -->
			<view class="phone-mode-tabs">
				<view class="phone-tab" :class="{ active: phoneLoginMode === 'code' }" @click="switchPhoneMode('code')">
					<text class="phone-tab-text">验证码登录</text>
				</view>
				<view class="phone-tab" :class="{ active: phoneLoginMode === 'password' }"
					@click="switchPhoneMode('password')">
					<text class="phone-tab-text">密码登录</text>
				</view>
			</view>

			<!-- 验证码登录 -->
			<view v-if="phoneLoginMode === 'code'" class="code-login-form">
				<view class="form-item">
					<view class="verify-code-wrapper">
						<input class="verify-input" v-model="phoneForm.verifyCode" placeholder="请输入6位验证码" type="number"
							maxlength="6" />
						<view class="verify-btn" :class="{ disabled: countdown > 0 || !isValidPhone(phoneForm.mobile) }"
							@click="sendVerifyCode">
							<text class="verify-btn-text">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 密码登录 -->
			<view v-if="phoneLoginMode === 'password'" class="password-login-form">
				<view class="form-item">
					<view class="input-wrapper">
						<text class="input-icon">🔒</text>
						<input class="form-input" v-model="phoneForm.password" placeholder="请输入登录密码"
							:password="!showPassword" />
						<text class="password-toggle"
							@click="togglePassword">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
					</view>
				</view>
			</view>

			<!-- 手机登录按钮 -->
			<view class="phone-login-btn-wrapper">
				<button class="auth-btn phone-btn" :class="{ disabled: !canPhoneLogin || phoneLoading }"
					@click="handlePhoneLogin" :disabled="!canPhoneLogin">
					<text class="btn-text">{{ phoneLoading ? '登录中...' : '立即登录' }}</text>
				</button>
			</view>
		</view>

		<!-- 用户协议 -->
		<view class="agreement-section">
			<view class="agreement-checkbox" @click="toggleAgreement">
				<text class="checkbox" :class="{ checked: agreedToTerms }">{{ agreedToTerms ? '✓' : '' }}</text>
				<text class="agreement-text">
					我已阅读并同意
					<text class="agreement-link" @click.stop="viewUserAgreement">《用户协议》</text>
					和
					<text class="agreement-link" @click.stop="viewPrivacyPolicy">《隐私政策》</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		validatePhone
	} from '@/common/validate.js'

	export default {
		data() {
			return {
				// 登录模式：wechat-微信登录，phone-手机登录
				loginMode: 'wechat',
				// 手机登录模式：code-验证码登录，password-密码登录
				phoneLoginMode: 'code',
				// 微信登录相关
				authLoading: false,
				auth_code: '',
				wxPhoneCode: '',
				wxUserInfo: {},
				// 手机登录相关
				phoneLoading: false,
				phoneForm: {
					mobile: '',
					verifyCode: '',
					password: ''
				},
				countdown: 0,
				showPassword: false,
				// 通用
				agreedToTerms: false,
				shopLogo: '/static/images/logo.png',
				isBack: false
			}
		},

		computed: {
			...mapGetters(['isLogin', 'openid', 'directid', 'dealerInfo']),

			// 是否可以进行手机登录
			canPhoneLogin() {
				if (!this.isValidPhone(this.phoneForm.mobile)) {
					return false
				}

				if (this.phoneLoginMode === 'code') {
					return this.phoneForm.verifyCode && this.phoneForm.verifyCode.length === 6
				} else {
					return this.phoneForm.password && this.phoneForm.password.length >= 6
				}
			}
		},

		onLoad(options) {
			// 检查是否已经登录			
			if (options.isBack) {
				this.isBack = options.isBack;
			}
			if (this.dealerInfo && this.dealerInfo.shop_logo && this.dealerInfo.shop_logo !== '') {
				this.shopLogo = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			}
			this.checkLoginStatus()
		},

		methods: {
			// 检查登录状态
			checkLoginStatus() {
				// 使用vuex中的登录状态
				if (this.isLogin && this.openid && this.openid != '') {
					// 已经登录，直接跳转到首页
					this.handleLoginSuccess()
				}
			},

			// 切换登录模式
			switchLoginMode(mode) {
				this.loginMode = mode
				// 清空手机登录表单
				if (mode === 'phone') {
					this.phoneForm = {
						mobile: '',
						verifyCode: '',
						password: ''
					}
					this.countdown = 0
				}
			},

			// 切换手机登录方式
			switchPhoneMode(mode) {
				this.phoneLoginMode = mode
				// 清空相关字段
				this.phoneForm.verifyCode = ''
				this.phoneForm.password = ''
				this.countdown = 0
			},

			getAuthCode() {
				// 获取登录凭证
				return new Promise((resolve, reject) => {
					this.auth_code = ''
					uni.login({
						provider: 'weixin', // 例如微信登录
						success: (loginRes) => {
							if (loginRes.code) {
								this.auth_code = loginRes.code
								resolve(loginRes); // 登录成功，解析返回结果
							} else {
								uni.showToast({
									title: '微信授权失败，请重试',
									icon: 'none'
								})
								reject('微信授权失败，请重试')
							}
						},
						fail: (err) => {
							uni.showToast({
								title: '微信授权失败，请重试',
								icon: 'none'
							})
							reject(err); // 登录失败，拒绝并返回错误
						}
						// complete 回调一般在这里不需要，因为 success/fail 之后 Promise 状态已定
					});
				});
			},

			// 验证手机号格式
			isValidPhone(phone) {
				return validatePhone(phone)
			},

			// 切换密码显示状态
			togglePassword() {
				this.showPassword = !this.showPassword
			},

			// 发送验证码
			async sendVerifyCode() {
				if (this.countdown > 0 || !this.isValidPhone(this.phoneForm.mobile)) {
					if (!this.isValidPhone(this.phoneForm.mobile)) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none'
						})
					}
					return
				}

				try {
					await this.$api.user.GetLoginVerifyCode({
						mobile: this.phoneForm.mobile
					})

					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					})

					this.startCountdown()
				} catch (error) {
					uni.showToast({
						title: error.message || '发送失败，请重试',
						icon: 'none'
					})
				}
			},

			// 开始倒计时
			startCountdown() {
				this.countdown = 60
				const timer = setInterval(() => {
					this.countdown--
					if (this.countdown <= 0) {
						clearInterval(timer)
					}
				}, 1000)
			},

			// 处理手机登录
			async handlePhoneLogin() {
				if (!this.agreedToTerms) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (!this.canPhoneLogin || this.phoneLoading) {
					return
				}

				this.phoneLoading = true
				await this.getAuthCode()

				try {
					let loginResult
					if (this.phoneLoginMode === 'code') {
						// 验证码登录
						loginResult = await this.$api.user.phoneCodeLogin({
							auth_code: this.auth_code,
							open_id: this.openid,
							mobile: this.phoneForm.mobile,
							captcha: this.phoneForm.verifyCode,
							directid: this.directid
						})
					} else {
						// 密码登录
						loginResult = await this.$api.user.phonePasswordLogin({
							auth_code: this.auth_code,
							open_id: this.openid,
							mobile: this.phoneForm.mobile,
							password: this.phoneForm.password,
							directid: this.directid
						})
					}

					// 登录成功的返回数据
					const newUserInfo = loginResult.data
					const openid = newUserInfo.openid
					// 使用vuex保存登录信息
					this.$store.dispatch('login', {
						openid: openid,
						userInfo: newUserInfo
					})

					// 同时保存到本地存储（兼容性）
					// uni.setStorageSync('openid', openid)
					// uni.setStorageSync('userInfo', newUserInfo)

					this.phoneLoading = false

					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})

					// 跳转页面
					this.handleLoginSuccess()
				} catch (error) {
					this.phoneLoading = false
					uni.showToast({
						title: error.message || '登录失败，请重试',
						icon: 'none'
					})
				}
			},

			// 登录成功后的处理
			handleLoginSuccess() {
				const pages = getCurrentPages()
				const prevPage = pages[pages.length - 2]
				if (this.isBack && prevPage) {
					// 回退上一页
					this.redirectToBack()
				} else {
					// 跳转到首页
					this.redirectToHome()
				}
			},

			// 微信授权获取用户信息
			async onGetUserInfo(e) {
				if (!this.agreedToTerms) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (e.detail.errMsg === 'getUserInfo:ok') {
					this.authLoading = true

					// 获取用户信息
					this.wxUserInfo = e.detail.userInfo
					console.log('获取用户信息', this.wxUserInfo)

					await this.getAuthCode()
					this.performLogin()
				} else {
					this.authLoading = false
					uni.showToast({
						title: '需要授权才能使用',
						icon: 'none'
					})
				}
			},

			// 微信授权获取手机号码
			async onGetPhoneNumber(e) {
				if (!this.agreedToTerms) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					this.authLoading = true

					// 获取手机号码
					this.wxPhoneCode = e.detail.code
					console.log('获取手机号码', this.wxPhoneCode)

					await this.getAuthCode()
					console.log('获取令牌', this.auth_code)

					this.performLogin()
				} else {
					this.authLoading = false
					uni.showToast({
						title: '需要授权才能使用',
						icon: 'none'
					})
				}
			},

			// 执行登录
			async performLogin() {
				try {
					// 获取用户登录信息
					this.$api.user.userRegister({
						auth_code: this.auth_code,
						open_id: this.openid,
						wxPhoneCode: this.wxPhoneCode,
						nickname: this.wxUserInfo.nickName || '微信用户',
						avatar_url: this.wxUserInfo.avatarUrl || '',
						directid: this.directid,
					}).then(res => {
						// 登录成功的返回数据
						const newUserInfo = res.data
						const openid = newUserInfo.openid
						// 使用vuex保存登录信息
						this.$store.dispatch('login', {
							openid: openid,
							userInfo: newUserInfo
						})

						// 同时保存到本地存储（兼容性）
						// uni.setStorageSync('openid', openid)
						// uni.setStorageSync('userInfo', newUserInfo)

						this.authLoading = false

						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})

						// 跳转页面
						this.handleLoginSuccess()
					}).catch(err => {
						this.authLoading = false
					})
				} catch (error) {
					this.authLoading = false
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					})
				}
			},

			// 跳转到首页
			redirectToHome() {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 1000)
			},

			// 回退上一页
			redirectToBack() {
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			},

			// 切换协议同意状态
			toggleAgreement() {
				this.agreedToTerms = !this.agreedToTerms
			},

			// 查看用户协议
			viewUserAgreement() {
				uni.navigateTo({
					url: '/pages/agreement/user-agreement'
				})
			},

			// 查看隐私政策
			viewPrivacyPolicy() {
				uni.navigateTo({
					url: '/pages/agreement/privacy-policy'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-container {
		min-height: 100vh;
		background: #ffffff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx;
		box-sizing: border-box;
	}

	/* Logo区域 */
	.logo-section {
		text-align: center;
		margin-bottom: 120rpx;
	}

	.logo {
		width: 120rpx;
		height: 120rpx;
		border-radius: 24rpx;
		background: #52a58a;
		background-image: url(@/static/images/logo.png);
		background-size: cover;
		background-position: center center;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 40rpx;
	}

	.logo-text {
		font-size: 48rpx;
		font-weight: bold;
		color: white;
	}

	.app-title {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
	}

	/* 登录模式切换 */
	.login-mode-tabs {
		display: flex;
		width: 100%;
		max-width: 600rpx;
		margin-bottom: 60rpx;
		background-color: #f8f9fa;
		border-radius: 50rpx;
		padding: 8rpx;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		border-radius: 42rpx;
		transition: all 0.3s ease;
	}

	.tab-item.active {
		background-color: white;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		font-weight: 500;
	}

	.tab-item.active .tab-text {
		color: #52a58a;
		font-weight: bold;
	}

	/* 微信登录区域 */
	.wechat-login-section {
		width: 100%;
		max-width: 600rpx;
		margin-bottom: 80rpx;
	}

	/* 手机登录区域 */
	.phone-login-section {
		width: 100%;
		max-width: 600rpx;
		margin-bottom: 80rpx;
	}

	/* 表单项 */
	.form-item {
		margin-bottom: 30rpx;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		border-radius: 50rpx;
		padding: 0 30rpx;
		height: 88rpx;
	}

	.input-icon {
		font-size: 32rpx;
		margin-right: 20rpx;
		color: #999;
	}

	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.password-toggle {
		font-size: 32rpx;
		color: #999;
		margin-left: 20rpx;
	}

	/* 手机登录方式切换 */
	.phone-mode-tabs {
		display: flex;
		margin-bottom: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.phone-tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		position: relative;
	}

	.phone-tab.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #52a58a;
		border-radius: 2rpx;
	}

	.phone-tab-text {
		font-size: 28rpx;
		color: #666;
	}

	.phone-tab.active .phone-tab-text {
		color: #52a58a;
		font-weight: bold;
	}

	/* 验证码输入 */
	.verify-code-wrapper {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		border-radius: 50rpx;
		padding: 0 30rpx;
		height: 88rpx;
	}

	.verify-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.verify-btn {
		background-color: #52a58a;
		color: white;
		padding: 16rpx 24rpx;
		border-radius: 30rpx;
		margin-left: 20rpx;
	}

	.verify-btn.disabled {
		background-color: #ccc;
	}

	.verify-btn-text {
		font-size: 24rpx;
		white-space: nowrap;
	}

	/* 登录按钮 */
	.auth-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(82, 165, 138, 0.3);
		transition: all 0.3s ease;
	}

	.auth-btn:disabled,
	.auth-btn.disabled {
		opacity: 0.6;
		box-shadow: none;
	}

	.btn-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
	}

	.btn-text {
		font-size: 32rpx;
		font-weight: bold;
	}

	.wechat-btn {
		background: linear-gradient(135deg, #07c160 0%, #1aad19 100%);
		box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
	}

	.phone-btn {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		box-shadow: 0 4rpx 12rpx rgba(82, 165, 138, 0.3);
	}

	/* 用户协议 */
	.agreement-section {
		width: 100%;
		max-width: 600rpx;
	}

	.agreement-checkbox {
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}

	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 6rpx;
		margin-right: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		color: white;
		flex-shrink: 0;
		margin-top: 4rpx;
	}

	.checkbox.checked {
		background: #52a58a;
		border-color: #52a58a;
		color: white;
	}

	.agreement-text {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.agreement-link {
		color: #52a58a;
		text-decoration: underline;
	}

	/* 响应式优化 */
	@media screen and (max-width: 750rpx) {
		.login-container {
			padding: 80rpx 40rpx 60rpx;
		}

		.logo-section {
			margin-bottom: 80rpx;
		}

		.login-mode-tabs {
			margin-bottom: 40rpx;
		}

		.tab-item {
			padding: 16rpx 0;
		}

		.tab-text,
		.phone-tab-text {
			font-size: 26rpx;
		}

		.input-wrapper,
		.verify-code-wrapper {
			height: 80rpx;
			padding: 0 24rpx;
		}

		.form-input,
		.verify-input {
			font-size: 26rpx;
		}

		.auth-btn {
			height: 80rpx;
			font-size: 28rpx;
		}

		.btn-text {
			font-size: 28rpx;
		}
	}

	/* 适配底部安全区域 */
	.login-container {
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
	}
</style>